package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.MemberSubscriptions;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.MemberSubscriptionsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 会员订阅接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/member-subscriptions")
@Slf4j
public class MemberSubscriptionsController {

    @Resource
    private MemberSubscriptionsService memberSubscriptionsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建会员订阅
     *
     * @param memberSubscriptions
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addMemberSubscription(@RequestBody MemberSubscriptions memberSubscriptions, HttpServletRequest request) {
        if (memberSubscriptions == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 校验必填字段
        Long userId = memberSubscriptions.getUserId();
        Integer subscriptionType = memberSubscriptions.getSubscriptionType();
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (subscriptionType == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "订阅类型不能为空");
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 设置默认值
        if (memberSubscriptions.getStatus() == null) {
            memberSubscriptions.setStatus(1);
        }
        if (memberSubscriptions.getAutoRenew() == null) {
            memberSubscriptions.setAutoRenew(0);
        }
        
        boolean result = memberSubscriptionsService.save(memberSubscriptions);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newMemberSubscriptionId = memberSubscriptions.getId();
        return ResultUtils.success(newMemberSubscriptionId);
    }

    /**
     * 删除会员订阅
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteMemberSubscription(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MemberSubscriptions oldMemberSubscription = memberSubscriptionsService.getById(id);
        ThrowUtils.throwIf(oldMemberSubscription == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = memberSubscriptionsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新会员订阅（仅管理员）
     *
     * @param memberSubscriptions
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMemberSubscription(@RequestBody MemberSubscriptions memberSubscriptions) {
        if (memberSubscriptions == null || memberSubscriptions.getId() == null || memberSubscriptions.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        boolean result = memberSubscriptionsService.updateById(memberSubscriptions);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取会员订阅
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<MemberSubscriptions> getMemberSubscriptionById(@RequestParam long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        MemberSubscriptions memberSubscription = memberSubscriptionsService.getById(id);
        if (memberSubscription == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 非管理员只能查看自己的订阅记录
        if (!userService.isAdmin(loginUser) && !memberSubscription.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        
        return ResultUtils.success(memberSubscription);
    }

    /**
     * 分页获取会员订阅列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MemberSubscriptions>> listMemberSubscriptionByPage(@RequestParam long current, @RequestParam long size) {
        Page<MemberSubscriptions> memberSubscriptionPage = memberSubscriptionsService.page(new Page<>(current, size));
        return ResultUtils.success(memberSubscriptionPage);
    }

    /**
     * 获取当前用户的订阅记录
     *
     * @param current
     * @param size
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<MemberSubscriptions>> listMyMemberSubscriptions(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            HttpServletRequest request) {
        
        User loginUser = userService.getLoginUser(request);
        Page<MemberSubscriptions> memberSubscriptionPage = memberSubscriptionsService.lambdaQuery()
                .eq(MemberSubscriptions::getUserId, loginUser.getId())
                .orderByDesc(MemberSubscriptions::getCreatedAt)
                .page(new Page<>(current, size));
        return ResultUtils.success(memberSubscriptionPage);
    }

    /**
     * 获取当前用户的有效订阅
     *
     * @param request
     * @return
     */
    @GetMapping("/my/active")
    public BaseResponse<MemberSubscriptions> getMyActiveSubscription(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        MemberSubscriptions activeSubscription = memberSubscriptionsService.lambdaQuery()
                .eq(MemberSubscriptions::getUserId, loginUser.getId())
                .eq(MemberSubscriptions::getStatus, 1)
                .orderByDesc(MemberSubscriptions::getExpireTime)
                .last("LIMIT 1")
                .one();
        return ResultUtils.success(activeSubscription);
    }

    /**
     * 根据用户ID获取订阅记录（仅管理员）
     *
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-user")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MemberSubscriptions>> listSubscriptionsByUserId(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID参数错误");
        }
        
        Page<MemberSubscriptions> memberSubscriptionPage = memberSubscriptionsService.lambdaQuery()
                .eq(MemberSubscriptions::getUserId, userId)
                .orderByDesc(MemberSubscriptions::getCreatedAt)
                .page(new Page<>(current, size));
        return ResultUtils.success(memberSubscriptionPage);
    }

    /**
     * 取消订阅自动续费
     *
     * @param subscriptionId
     * @param request
     * @return
     */
    @PostMapping("/cancel-auto-renew")
    public BaseResponse<Boolean> cancelAutoRenew(@RequestParam Long subscriptionId, HttpServletRequest request) {
        if (subscriptionId == null || subscriptionId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        User loginUser = userService.getLoginUser(request);
        MemberSubscriptions subscription = memberSubscriptionsService.getById(subscriptionId);
        if (subscription == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 非管理员只能操作自己的订阅
        if (!userService.isAdmin(loginUser) && !subscription.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        
        subscription.setAutoRenew(0);
        boolean result = memberSubscriptionsService.updateById(subscription);
        return ResultUtils.success(result);
    }

    /**
     * 编辑会员订阅（给管理员使用）
     *
     * @param memberSubscriptions
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editMemberSubscription(@RequestBody MemberSubscriptions memberSubscriptions, HttpServletRequest request) {
        if (memberSubscriptions == null || memberSubscriptions.getId() == null || memberSubscriptions.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        MemberSubscriptions oldMemberSubscription = memberSubscriptionsService.getById(memberSubscriptions.getId());
        ThrowUtils.throwIf(oldMemberSubscription == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = memberSubscriptionsService.updateById(memberSubscriptions);
        return ResultUtils.success(result);
    }

    // endregion
}